package com.usian.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usian.common.constans.wemedia.WemediaContans;
import com.usian.common.dtas.BaseServiceImpl;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmNewsDto;
import com.usian.model.media.dtos.WmNewsPageReqDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNews;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.threadlocal.AdminThreadLocalUtils;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.service.WmNewsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class WmNewsServiceImpl extends BaseServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Value("${fdfs.url}")
    private String fileServerUrl;

    @Override
    /**
     * 查询所有自媒体文章
     * @return
     */
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        if (dto == null) return ErrorParam;
        Page page = new Page(dto.getPage(), dto.getSize());
        //分页查询条件
        LambdaUpdateWrapper<WmNews> wrapper = new LambdaUpdateWrapper<>();
        //查询状态
        wrapper.eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus());
        //查询频道id
        wrapper.eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId());
        //模糊关键字查询
        wrapper.like(dto.getKeyword() != null, WmNews::getTitle, dto.getKeyword());
        //如果maxtime==null 给这个时间一个当前时间
        if (dto.getMaxTime() == null) dto.setMaxTime(new Date());
        //查询的是小于发布时间的信息
        wrapper.lt(WmNews::getPublishTime, dto.getMaxTime());
        wrapper.orderByDesc(WmNews::getPublishTime);
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "用户不存在");
        }
        wrapper.eq(WmNews::getUserId, user.getId());
        wrapper.orderByDesc(WmNews::getCreatedTime);
        IPage page1 = page(page, wrapper);
        //3.结果封装返回
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page1.getTotal());
        responseResult.setData(page1.getRecords());
//        responseResult.setHost(fileServerUrl);
        return responseResult;

    }

    @Value("${fdfs.url}")
    private String FdfsUrl;
    @Autowired
    WmMaterialMapper wmMaterialMapper;
    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    @Override
    public ResponseResult saveNews(WmNewsDto wmNews) {
        //1.检查参数
        if (wmNews == null) return ErrorParam;
        if (wmNews.getType() == -1) wmNews.setType(null);
        //新增文章
        WmNews news = new WmNews();
        //新增新闻克隆到wmNews1
        BeanUtils.copyProperties(wmNews, news);
        news.setUserId(WmThreadLocalUtils.getUser().getId());
        news.setSubmitedTime(new Date());
        news.setCreatedTime(new Date());
        //如果id为null
        if (wmNews.getId() == null) {
            //则新增新闻
            save(news);
        } else {
            updateById(news);
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, news.getId()));
        }
        saveRelations(news, wmNews);
        return Success;
    }

    private void saveRelations(WmNews saveNews, WmNewsDto wmNewsDto) {
        //拿到新闻id
        Long newsId = saveNews.getId();
        //获取到文章内容
        String content = saveNews.getContent();
        //转为JSONArray
        JSONArray array = JSON.parseArray(content);
        //定义一个集合存储文章内容的图片
        List<String> listcontent = new ArrayList<>(); //这是所有文章内容的图片
        //通过获取到文章内容获取到value内容的图片路径
        array.forEach(o -> {
            JSONObject object = JSON.parseObject(o.toString());
            if (object.getString("type").equals("image")) {
                String value = object.getString("value");
                listcontent.add(value.replace(FdfsUrl, ""));
            }

        });
        moreInsert(newsId, listcontent, WemediaContans.WM_CONTENT_REFERENCE);
        WmNews news = new WmNews();
        //已经保存图片和内容已经处理 ，下面保存封面图和新闻id
        if (wmNewsDto.getType() != null) {//前端没选自动 //如果 type不是 -1 自动
            List<String> images = wmNewsDto.getImages();
            if (images != null && images.size() != 0) {
                //  images.forEach(i->i=i.replace(FdfsUrl,""));
                images = images.stream().map(i -> i = i.replace(FdfsUrl, "")).collect(Collectors.toList());
                moreInsert(newsId, images, WemediaContans.WM_COVER_REFERENCE);
            }
            //如果是多图的情况下对图片进行处理
            StringBuilder builder = new StringBuilder();
            for (String url : images) {
                builder.append(url).append(",");
            }
            String imageStr = builder.toString().substring(0, builder.toString().length() - 1);
            news.setImages(imageStr);
            news.setId(saveNews.getId());
            updateById(news);
        } else {//根据内容里的图片数量来决定封面是几张图  //自动
            //如果图片长度不等与0的话，size小于3 则向是单图
            news.setId(newsId);
            if (listcontent.size() != 0) {
                //如果内容图片小于三则取内容中单图，否则取多图
                List<String> autoCoverUrls = listcontent.size() < 3 ? Arrays.asList(listcontent.get(0)) :
                        Arrays.asList(listcontent.get(0), listcontent.get(1), listcontent.get(2));
                moreInsert(newsId, autoCoverUrls, WemediaContans.WM_COVER_REFERENCE);
                StringBuilder builder = new StringBuilder();
                for (String url : autoCoverUrls) {
                    builder.append(url).append(",");
                }
                String imageStr = builder.toString().substring(0, builder.toString().length() - 1);
                news.setImages(imageStr);
                //如果图片小于3则是单图，不小于三则多图
                news.setType(autoCoverUrls.size() < 3 ? WemediaContans.WM_NEWS_SINGLE_IMAGE : WemediaContans.WM_NEWS_MANY_IMAGE);

            } else {
                news.setImages("");
                news.setType(WemediaContans.WM_NEWS_NONE_IMAGE);

            }
            updateById(news);
        }

    }

    private void moreInsert(Long newsId, List<String> listcontent, Short reference) {
        //查询到当前用户登录的素材列表 v
        LambdaUpdateWrapper<WmMaterial> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId());
        wrapper.in(WmMaterial::getUrl, listcontent);
        //获取到新增新闻的图片路径查找素材列表中的信息
        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(wrapper);
        //通过strem流把列表中的id封装到新的集合中
        List<String> ids = wmMaterials.stream().map(m -> m.getId() + "").collect(Collectors.toList());
        wmNewsMaterialMapper.saveRelationsByContent(ids, newsId, reference);
    }
}
